/*
Author: Jason Bareswilt
Functionality: to keep track of all the highscores
Version number: 0.0.3
Testers: needs to be tested
Date written: November 22nd 2011
Date tested: needs to be tested
*/
package disease;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;


public class HighScorelog 
{
	public static Map<Integer, String> scoreList = new TreeMap<Integer, String>(Collections.reverseOrder());
	
	public static void updateScores(String[] args)
	{
		try
		{
			FileInputStream fstream = new FileInputStream("Scores.csv");
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			while ((strLine = br.readLine()) != null)   
			{
				scoreList.put(Integer.parseInt(strLine.split(",")[0]), strLine.split(",")[1]);
			}
			fstream.close();
			in.close();
			br.close();
		}
		catch (Exception e)
		{
			System.err.println("Error: " + e.getMessage());
		}
				
		try 
		{
			int lineCounter = 0;
		    BufferedReader br = new BufferedReader(new FileReader("Scores.csv"));
			BufferedWriter out = new BufferedWriter(new FileWriter("Scores.csv"));		
			while ((br.readLine()) != null)
			{
				out.flush();
			}			
			Set<Entry<Integer, String>> set = scoreList.entrySet();
			Iterator<Entry<Integer, String>> i = set.iterator();
			while(i.hasNext())
			{
				if (lineCounter == 10)
					break;
				Map.Entry<Integer, String> me = (Map.Entry<Integer, String>)i.next();
				System.out.println(me.getKey() + "," + me.getValue());
				out.write(me.getKey() + "," + me.getValue());
				out.write(System.getProperty("line.separator"));
				lineCounter++;
			}
			br.close();
			out.close();
		}
		catch (IOException e)
		{
			System.out.println("Exception ");
		}
	}
	
	public static void addScore(String name, int score)
	{
		System.out.println("in add score");
		try
		{
			BufferedWriter out = new BufferedWriter(new FileWriter("Scores.csv",true));
			String newLine = score + "," + name;
			out.write(newLine);
			out.close();
		}
		catch (IOException e)
		{
			System.out.println("Exception ");
		}
		updateScores(null);
		
	}
	
	public static void resetScores()
	{
		try
		{
			BufferedReader br = new BufferedReader(new FileReader("Scores.csv"));
			BufferedWriter out = new BufferedWriter(new FileWriter("Scores.csv"));
			while ((br.readLine()) != null)
			{
				out.flush();
			}
			
			br.close();
			out.close();
		}
		catch (IOException e)
		{
			System.out.println("Exception ");
		}
	}
}